package com.baijia.authentication.principal.populator;

import com.baijia.authentication.Authentication;
import com.baijia.authentication.AuthenticationMetaDataPopulator;
import com.baijia.authentication.principal.Credentials;
import com.baijia.authentication.principal.credentials.JigouCredentials;
import com.baijia.dao.OrgAccountDao;
import com.baijia.dao.po.OrgAccount;
import com.baijia.util.JacksonUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * @title JigouAccountMetaDataPopulator
 * @desc 补充authentication信息，从credentials获得
 * @author caoliang
 * @date 2015年11月12日
 * @version 1.0
 */
@Component
public final class JigouAccountMetaDataPopulator implements AuthenticationMetaDataPopulator{
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    private static final String ORG_ACCOUNT = "orgAccount";
    
    @Autowired
    private OrgAccountDao orgAccountDao;
    
	@Override
	public Authentication populateAttributes(Authentication authentication,
			Credentials credentials) {
	    
	    JigouCredentials jigouCredentials = (JigouCredentials) credentials;
        String mobile = jigouCredentials.getUsername();
        String countryCode = jigouCredentials.getCountryCode();
        
        logger.debug("Try to populate jigouAccount username:{},countryCode:{}", mobile, countryCode);
        OrgAccount orgAccount = orgAccountDao.findByMobile(mobile, countryCode);
        authentication.getAttributes().put(ACCOUNT_ID, orgAccount.getId());
        authentication.getAttributes().put(ACCOUNT_NUMBER, orgAccount.getNumber());
        try {
            orgAccount.setPassword(null);
            authentication.getAttributes().put(ORG_ACCOUNT, JacksonUtil.obj2Str(orgAccount));
        } catch (IOException e) {
            logger.error("save orgAccount into dession error!", e);
        }
	    return authentication;
	}

    public void setOrgAccountDao(OrgAccountDao orgAccountDao) {
    
        this.orgAccountDao = orgAccountDao;
    }

    @Override
    public boolean supports(Credentials credentials) {
        return credentials instanceof JigouCredentials;
            
    }
}
